#include "EDDemo.h"
#include "vec3.h"
#include "matrix4.h"
#include <iostream>

void EDDemo::Initialize(void)
{
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
    glEnable(GL_CULL_FACE);
 	glEnableClientState(GL_VERTEX_ARRAY);
 	glEnableClientState(GL_NORMAL_ARRAY);

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	float noLight[] = { 0, 0, 0, 0};
	float allLight[] = { 1, 1, 1, 1};
	float posLight[] = { 0, 0, 0, 1};
	glLightfv(GL_LIGHT0, GL_AMBIENT, noLight);
	glLightfv(GL_LIGHT0, GL_SPECULAR, noLight);
	glLightfv(GL_LIGHT0, GL_DIFFUSE, allLight);
	glLightfv(GL_LIGHT0, GL_POSITION, posLight);


	// Load the animation
	m_Animation.LoadFromFile("test.eda");
	// Attach the animation to the interpolator
	m_Interpolator.SetAnimation(&m_Animation);
	m_Model.LoadMeshsFromFile("test.edm");
}

void EDDemo::Shutdown(void)
{
	exit(0);
}

void EDDemo::Display(void)
{    
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
        m_Camera.applyCameraMatrix();

		// Add time to our interpolator
		m_Interpolator.AddTime(0.015f);	// Doesnt have to be time based
		 //Interpolate our animation
		m_Interpolator.Process();
// TO DO

		unsigned int meshNum = m_Model.GetMeshNum();

		for(unsigned int i = 0; i < meshNum; ++i)
		{
			glPushMatrix();
			glMultMatrixf((m_Interpolator.GetCurrKeyFrame()->nodeVec[i].ma));

			// Current mesh
			Mesh* currMesh = const_cast<Mesh*>(m_Model.GetMesh(i));

			//Draw the interpolator's current state.
			glVertexPointer(3, GL_FLOAT, 0, &(currMesh->GetVertices().front()));
			glNormalPointer(GL_FLOAT, 0, &(currMesh->GetNormals().front()));

			glDrawArrays(GL_TRIANGLES, 0, currMesh->GetVertices().size());

			glPopMatrix();
		}

		// Draws the ground.
		float width = 20.0f;
		float y = -30.0f;
		float step = 1.f;
		glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
		for(float x = -width; x <= width; x += step)
		{
			glBegin(GL_TRIANGLE_STRIP);
			for(float z = -width; z <= width; z += step)
			{
				glNormal3f(0.0f, 1.0f, 0.0);
				glVertex3f(x + step, y, z);
				glVertex3f(x, y, z);            
			}
			glEnd();
		}

    glPopMatrix();
    glutSwapBuffers();
}

void EDDemo::Idle(void)
{
	if(GetAsyncKeyState(VK_ESCAPE))
        Shutdown();
    m_Camera.update();
    glutPostRedisplay();
}

void EDDemo::Menu(int value)
{  
    if(value == 0)
        Shutdown(); 
    glutPostRedisplay();
}
